package other.system.client.oa.submit;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.rkhd.platform.sdk.data.model.Quote;
import com.rkhd.platform.sdk.log.Logger;
import com.rkhd.platform.sdk.log.LoggerFactory;
import com.rkhd.platform.sdk.model.QueryResult;
import com.rkhd.platform.sdk.service.XoqlService;
import org.apache.commons.lang.StringUtils;
import other.system.client.util.HCXObjectService;
import other.system.client.util.ResultBody;
import other.system.client.util.TfReturnMsgTools;

import java.util.*;

/**
 * @Description: 提交报价单模块
 * @Author: 黎炎松
 * @Date: 2024/7/9 17:36
 */
public class SubmitQuote extends SubmitSuper {
    private static HCXObjectService hcxObjectService = new HCXObjectService();

    private static XoqlService xoqlService = XoqlService.instance();

    private static final String LOGGER_MSG = "推送报价单审批数据到OA ==> ";

    private static final Logger logger = LoggerFactory.getLogger();

    public static void main(String[] args) {
        // 需切换测试环境进行测试，正式环境发送会导致他们的人员账号收到审批提醒
        new SubmitQuote().pushQuoteToOA(3461282661735020L);
    }


    /**
     * 推送报价单数据到OA审批 quote
     * @param
     * @return
     */
    public String pushQuoteToOA(Long quoteId) {
        try {
            logger.info(LOGGER_MSG + "处理开始: " + quoteId);

            // 获取报价单信息
            String sql = "select name,quotationTitle,pmsProjectNo__c,departmentTeam__c,sealSubject2__c.name sealSubjectName,stampedQuantity__c,sealReason__c," +
                    "sealType__c,YNKa__c,paymentMethodA__c,quotationEntityRelAccount.accountName quotationEntityRelAccountName,quotationAmount,attachments__c," +
                    "oaApprovalId__c,oaApprovalStatus__c,entityType,countersignNode__c.LoginName__c oaAccount,countersignNode__c.personalEmail oaEmail," +
                    "ownerId.LoginName__c ownerOaAccount,ownerId.personalEmail ownerOaEmail,quoteRelContact,approximateSum__c " +
                    "from quote where id = " + quoteId;
            QueryResult<JSONObject> query = xoqlService.query(sql, true);
            List<JSONObject> records = query.getRecords();
            if (records.size() <= 0) {
                logger.error(LOGGER_MSG + "获取报价单数据异常");
                return TfReturnMsgTools.getFailResult("获取报价单数据异常:" + query.getErrorMessage());
            }

            // 获取报价单字段信息
            JSONObject quote = records.get(0);
            Long entityType = quote.getLong("entityType"); // 业务类型
            String quotationTitle = quote.getString("quotationTitle"); // 标题
            String oaApprovalId = quote.getString("oaApprovalId__c"); // 审批id
            String oaApprovalStatus = getOptionStr(quote.getJSONArray("oaApprovalStatus__c"));
            // 如果是 作废 状态，则重新提交
            if (Objects.equals(oaApprovalStatus, "作废")) {
                oaApprovalId = "";
            }
            logger.info(LOGGER_MSG + "quoteObj: " + quote);

            // 判断业务类型  只推送 项目报价类 3203859641306480L
            if (entityType != 3203859641306480L) {
                logger.error(LOGGER_MSG + "当前报价单业务类型不可提交OA审批");
                return TfReturnMsgTools.getFailResult("当前报价单业务类型不可提交OA审批");
            }

            // 判断字段必填
            List<String> tipsList = new ArrayList<>();
            Map<String, String> fieldMap = new LinkedHashMap<String, String>(){{
                put("paymentMethodA__c", "付款方式");
                put("sealSubjectName", "盖章主体");
                put("sealType__c", "印章类型");
                put("attachments__c", "附件");
                put("quoteRelContact", "联系人姓名");
            }};
            for (String key : fieldMap.keySet()) {
                if (quote.get(key) == null || StringUtils.isBlank(quote.getString(key))) {
                    tipsList.add(fieldMap.get(key));
                }
            }

            if (tipsList.size() > 0) {
                String tips = StringUtils.join(tipsList, ",");
                logger.error(LOGGER_MSG + "必填字段不可为空: " + tips);
                return TfReturnMsgTools.getFailResult(String.format("推送字段不可为空(%s)", tips));
            }

            // 判断 【所属部门/团队】 是否为空，进行提示
            String departmentTeamVal = quote.getString("departmentTeam__c");
            if (StringUtils.isBlank(departmentTeamVal)) {
                logger.error(LOGGER_MSG + "当前数据【所有人】部门下的'项目所属部门团队'为空，请联系管理员进行配置");
                return TfReturnMsgTools.getFailResult("当前数据【所有人】部门下的'项目所属部门团队'为空，请联系管理员进行配置");
            }

            // 获取报价单明细信息
            sql = "select id,materialCode__c,quotationDetailEntityRelProduct.productName productName,lineDescription__c,productNameA__c," +
                    "specificationModel__c,unit__c,unitA__c,quantity2__c,price,taxRate_1__c,excludingTaxAmount__c,amount,cycle__c " +
                    " from quoteLine where quotationDetailEntityRelQuotationEntity = " + quoteId;
            QueryResult<JSONObject> quoteLineQuery = xoqlService.query(sql);
            List<JSONObject> quoteLineList = quoteLineQuery.getRecords();
            logger.info(LOGGER_MSG + "quoteLineList: " + quoteLineList.size());
            if (quoteLineList.size() <= 0) {
                logger.error(LOGGER_MSG + "报价单明细不可为空");
                return TfReturnMsgTools.getFailResult("报价单明细不可为空");
            }

            // 拼接表单的数据
            JSONObject formObject = new JSONObject();
            formObject.put("fd_3d1be39194a794", quote.getString("name")); // 报价单编号
            formObject.put("fd_37b206a1075000", quotationTitle); // 报价单名称
            formObject.put("fd_389b41aaed4cae", quote.getString("pmsProjectNo__c")); // 业务机会项目编码
            formObject.put("fd_385c5756ba0d94", departmentTeamVal); // 所属部门/团队
            formObject.put("fd_37cecf1252aa7a", quote.getString("sealSubjectName")); // 盖章主体
            formObject.put("fd_37b206c9607924", quote.getString("stampedQuantity__c")); // 盖章数量
            formObject.put("fd_37b206a8f5cdf6", quote.getString("sealReason__c")); // 盖章原因
            formObject.put("fd_3b5ce1800cdca4", getOptionStr(quote.getJSONArray("sealType__c"))); // 印章类型
            formObject.put("fd_37fe192743a588", getOaAccount(quote, 1)); // 加签节点
            formObject.put("fd_3cb12aab88898c", quote.getString("YNKa__c")); // 是否KA
            formObject.put("fd_3d0ace29c722b6", quote.getString("paymentMethodA__c")); // 付款方式
            formObject.put("fd_3d0ace78c5b5dc", quote.getString("quotationEntityRelAccountName")); // 客户名称
            formObject.put("fd_3d0ad17dc9cd98", quote.getString("quotationAmount")); // 合计报价总金额
            formObject.put("fd_3d5d4d6b9a4cc4", quote.getString("approximateSum__c")); // 与概算是否一致

            // 明细数据
            JSONArray quoteLineArr = new JSONArray();
            for (JSONObject quoteLine : quoteLineList) {
                JSONObject quoteLineObj = new JSONObject();
                quoteLineObj.put("fd_3d0acf0d217338.fd_3d0ad11d46e63c", quoteLine.getString("materialCode__c")); // 物料编码
                quoteLineObj.put("fd_3d0acf0d217338.fd_3d0ad120c87d30", quoteLine.getString("productName")); // 产品名称（系统）
                quoteLineObj.put("fd_3d0acf0d217338.fd_3d0ad12159b114", quoteLine.getString("productNameA__c")); // 产品名称
                quoteLineObj.put("fd_3d0acf0d217338.fd_3d0ad12214b358", quoteLine.getString("specificationModel__c")); // 规则型号

                // 单位
                String unit = quoteLine.getString("unitA__c");
                if (StringUtils.isBlank(unit) && quoteLine.get("unit__c") != null) {
                    unit = getOptionStr(quoteLine.getJSONArray("unit__c"));
                }
                quoteLineObj.put("fd_3d0acf0d217338.fd_3d0ad12311fe2e", unit);

                quoteLineObj.put("fd_3d0acf0d217338.fd_3d0ad123c44ee2", quoteLine.getString("quantity2__c")); // 数量
                quoteLineObj.put("fd_3d0acf0d217338.fd_3d0ad1247b7bbc", quoteLine.getString("price")); // 单价
                quoteLineObj.put("fd_3d0acf0d217338.fd_3d0ad125453072", getOptionStr(quoteLine.getJSONArray("taxRate_1__c"))); // 税率
                quoteLineObj.put("fd_3d0acf0d217338.fd_3d0ad12615fc80", quoteLine.getString("excludingTaxAmount__c")); // 合同总价（不含税）
                quoteLineObj.put("fd_3d0acf0d217338.fd_3d0ad12738f778", quoteLine.getString("amount")); // 合同总价（含税）
                quoteLineObj.put("fd_3d0acf0d217338.fd_3d0ad129e2e734", quoteLine.getString("cycle__c")); // 质保期限/服务期限
                quoteLineObj.put("fd_3d0acf0d217338.fd_3d0ad12d30fefc", quoteLine.getString("lineDescription__c")); // 产品描述

                quoteLineArr.add(quoteLineObj);
            }
            formObject.put("fd_3d0acf0d217338", quoteLineArr);
            logger.info(LOGGER_MSG + "formObject: " + formObject);

            // 获取所有人的OA账号 发送请求
            JSONObject ownerOaAccount = getOaAccount(quote, 2);
            ResultBody resultBody = pushReqToOa("quote", quotationTitle, oaApprovalId, ownerOaAccount, formObject, null);
            logger.info(LOGGER_MSG + "resultBody: " + resultBody);
            if (!Objects.equals(resultBody.getCode(), "200")) {
                logger.error(LOGGER_MSG + "推送报价单数据到OA异常: " + resultBody.getMessage());
                return TfReturnMsgTools.getFailResult("推送报价单数据到OA异常:" + resultBody.getMessage());
            }

            // 返回的 id 进行保存
            String newOAId = resultBody.getResult().toString();
            Quote upQuote = new Quote();
            upQuote.setId(quoteId);
            upQuote.setOaApprovalId__c(newOAId);
            upQuote.setOaApprovalStatus__c(1);
            upQuote.setLockStatus(2);
            Boolean update = hcxObjectService.update(upQuote);
            logger.info(LOGGER_MSG + "update: " + update);

            // 撤回后重新提交需要修改OA的数据状态为 已提交
            if (StringUtils.isNotBlank(oaApprovalId) && (Objects.equals(oaApprovalStatus, "撤回") || Objects.equals(oaApprovalStatus, "驳回"))) {
                resubmitApprovalData(oaApprovalId, ownerOaAccount);
            }

            // 单独的方法更新附件
            JSONArray fileList = quote.getJSONArray("attachments__c"); // 附件
            UploadOAFile.syncUoloadFile(newOAId, fileKeyMap.get("quote"), fileList);

            logger.info(LOGGER_MSG + "提交成功");
            return TfReturnMsgTools.getSuccessResult("提交成功");
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(LOGGER_MSG + "处理异常: " + e.getMessage());
            return TfReturnMsgTools.getFailResult("推送异常:" + e.getMessage());
        }
    }


}
